package com.yicong.ants.ui.coin;

import android.content.DialogInterface;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import androidx.core.widget.NestedScrollView;

import com.amap.api.location.AMapLocation;
import com.cchao.simplelib.core.PrefHelper;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.util.StringHelper;
import com.cchao.simplelib.util.UrlUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.activity.DoubleConfirmActivity;
import com.yicong.ants.bean.base.RespBean;
import com.yicong.ants.bean.coin.LastTrans;
import com.yicong.ants.bean.coin.SearchUidTrans;
import com.yicong.ants.bean.coin.TransInfo;
import com.yicong.ants.databinding.TransActivityBinding;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.ad.AdManager;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.ui.me.PayPwdSettingActivity;
import com.yicong.ants.utils.AmapHelper;
import com.yicong.ants.utils.GuideHelper;
import com.yicong.ants.view.component.SimpleComponent;
import com.yicong.ants.view.dialog.CompleteLastNameDialog;
import com.yicong.ants.view.dialog.TransferTipsDialog;
import com.zx.sdk.util.ConfigHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;

/**
 * @author cch
 * @version 2020/8/22
 */
public class TransActivity extends BaseTitleBarActivity<TransActivityBinding> implements View.OnClickListener {
    TransInfo mTransInfo;
    boolean mCurCoinType = false;

    @Override
    protected int getLayout() {
        return R.layout.trans_activity;
    }

    @Override
    protected void initEventAndData() {
        setTitleText("门票转赠");
        setTitleBarVisible(false);

        mDataBind.mScrollView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom,
                                       int oldLeft, int oldTop, int oldRight, int oldBottom) {
                v.removeOnLayoutChangeListener(this);
                mDataBind.layoutGroup.setMinimumHeight(v.getHeight());
            }
        });

        AppHelper.transStatus(getWindow());
        String uid = getIntent().getStringExtra(Constants.Extra.Uid);
        if (StringHelper.isNotEmpty(uid)) {
            mDataBind.toUid.setText(uid);
            mCurCoinType = false;
        }
        mDataBind.swipeRefresh.setOnRefreshListener(this::onLoadData);
        mDataBind.transferDescription.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
//        onLoadData();
        setGive();
        initTitleChange();
        if (ConfigHelper.getShowInterstitialPages().contains("warehouseDonate")) {
            AdManager.showInterstitial(this);
        }
    }

    private void initTitleChange() {
        mDataBind.mScrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            float alp = scrollY * 0.02f;
            if (alp < 0) {
                alp = 0;
            } else if (alp > 1) {
                alp = 1;
            }
            mDataBind.titleBgImage.setAlpha(alp);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        onLoadData();
    }

    private void initStep() {
        if (!UserManager.getUserBean().getIsAuth()) {
            return;
        }

        if (!PrefHelper.isFirstTimes(Constants.Prefs.task_step4)) {
            return;
        }

        mDataBind.energyField.post(() -> {
            SimpleComponent component = new SimpleComponent();
            component.setContent("看广告视频加活跃度");
            GuideHelper.showCircleGuideView(thisActivity, 12, mDataBind.energyField, component);
        });
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Auth_Suc:
                onLoadData();
                break;
        }
    }

    private void updateInfo() {
        mDataBind.setClick(this);
        mDataBind.setUser(mTransInfo);
        mDataBind.transCoin.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                numberChanged();
                if (StringHelper.isEmpty(s)) {
                    mDataBind.deductTaxCoin.setText("0 门票");
                    mDataBind.totalDeductCoin.setText("0 门票");
                    return;
                }
                //转赠手续费
                BigDecimal bigDecimal = new BigDecimal(s.toString());
                BigDecimal sx = bigDecimal.multiply(new BigDecimal(Float.toString(mTransInfo.getTrans_tax())));
                double coinAmount = bigDecimal.add(sx).setScale(5, RoundingMode.DOWN).doubleValue();
                try {
                    double canTransCoin = mCurCoinType ? Double.parseDouble(mTransInfo.getCan_trans_coin()) : Double.parseDouble(mTransInfo.getStock());
                    if (coinAmount > canTransCoin) {
                        showToast("超出最大可转赠门票");
                        mDataBind.deductTaxCoin.setText("门票不足");
//                        mDataBind.deductTaxCoin.setTextColor(UiHelper.getColor(R.color.red_primary));
                        mDataBind.totalDeductCoin.setText(coinAmount + " 门票");
                        return;
                    }
                    if (mCurCoinType) {
                        mDataBind.deductTaxCoin.setText(BusinessHelper.calTax((float) coinAmount, mTransInfo.getTax_level()).first + " 门票");
                        mDataBind.totalDeductCoin.setText(BusinessHelper.calTax((float) coinAmount, mTransInfo.getTax_level()).second + " 门票");
                    } else {
                        mDataBind.deductTaxCoin.setText("0 门票");
                        mDataBind.totalDeductCoin.setText(coinAmount + " 门票");
                    }
                } catch (Exception ex) {

                }
            }
        });
        UiHelper.setVisibleElseGone(mDataBind.payCodeField, mTransInfo.getNeed_code_verify() == 1);
        UiHelper.setVisibleElseGone(mDataBind.payPwdField, mTransInfo.getNeed_code_verify() == 0);
        UiHelper.setVisibleElseGone(mDataBind.pwfLine, mTransInfo.getNeed_code_verify() == 0);

        if (mTransInfo.getHave_pay_password() == 0) {
            UiHelper.showConfirmActionDialog(mContext, "您还没有设置支付密码，是否前往设置", (dialog, which) -> {
                //
                Router.turnTo(mContext, PayPwdSettingActivity.class)
                        .start();
                finish();
            });
        }
//        initStep();
    }

    private void numberChanged() {
        if (mDataBind.transCoin.getText() == null || "".equals(mDataBind.transCoin.getText().toString())) {
            mDataBind.transCoin.setTypeface(Typeface.DEFAULT);
        } else {
            mDataBind.transCoin.setTypeface(Typeface.DEFAULT_BOLD);
        }

    }

    @Override
    protected void onLoadData() {
        if (mTransInfo == null) {
            switchView(LOADING);
        } else {
            showProgress();
        }
        addSubscribe(RetrofitHelper.getApis().tranInfo(Collections.emptyMap())
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    mDataBind.swipeRefresh.setRefreshing(false);
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                        switchView(NET_ERROR);
                        return;
                    }
                    switchView(CONTENT);
                    mTransInfo = respBean.getData();
                    updateInfo();
                    toggleSourceType(mCurCoinType);
                }, throwable -> {
                    mDataBind.swipeRefresh.setRefreshing(false);
                    if (mTransInfo == null) {
                        switchView(NET_ERROR);
                    }
                }));
    }

    void countDownVerifyCode() {
        RxHelper.countDownConsumer(60, intValue -> {
            //
            mDataBind.verifyCode.setText((60 - intValue) + " s");
        }, () -> {
            //
            mDataBind.verifyCode.setText("获取验证码");
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                onBackPressed();
                break;
            case R.id.coin_type_filed:
            case R.id.stock_refresh:
                mDataBind.swipeRefresh.setRefreshing(true);
                RxHelper.timerConsumer(1000, aLong -> onLoadData());
                break;
            case R.id.search:
                if (StringHelper.isEmpty(mDataBind.toUid.getText())) {
                    showToast("请填写好友账号");
                    return;
                }
                showProgress();
                Map<String, String> map2 = new HashMap<>();
                map2.put("s_uid", mDataBind.toUid.getText().toString());
                addSubscribe(RetrofitHelper.getApis().searchById(map2)
                        .compose(RxHelper.toMain())
                        .subscribe(respBean -> {
                            hideProgress();
                            if (respBean.isCodeFail()) {
                                UiHelper.setVisibleElseGone(mDataBind.searchUserField, false);
                                showToast(respBean.getMsg());
                                return;
                            }
                            SearchUidTrans bean = respBean.getData();
                            mDataBind.setSearchUidTrans(bean);
                            mDataBind.userInfoText.setText(bean.getId_card_name() + "    " + bean.getMobile());
                            mDataBind.userInfoRole.setText(bean.getRole_text());
                            mDataBind.wxAccount.setText(bean.getWx_account());
                            mDataBind.wxAccount.setTextColor(UiHelper.getColor(bean.getWx_danger() == 1 ? R.color.red_text_color : R.color.green_text_color));
                            mDataBind.userInfoRole.setNormalTextColor(UiHelper.getColor(bean.getRole() == 1 ? R.color.green_text_color : R.color.bluePrimary));
                            mDataBind.userInfoRole.setNormalStrokeColor(UiHelper.getColor(bean.getRole() == 1 ? R.color.green_text_color : R.color.bluePrimary));
                            UiHelper.setVisibleElseGone(mDataBind.userInfoRole, StringHelper.isNotEmpty(bean.getRole_text()));
                            UiHelper.setVisibleElseGone(mDataBind.searchUserField, true);
                            UiHelper.setVisibleElseGone(mDataBind.niceNumber, mDataBind.toUid.getText().toString().length() < 8);
                            UiHelper.setVisibleElseGone(mDataBind.wxAccount, StringHelper.isNotEmpty(bean.getWx_account()));

                        }, RxHelper.getHideProgressConsumer(this)));
                break;
            case R.id.trans_all:
                if (mCurCoinType) {
                    mDataBind.transCoin.setText(String.valueOf(mTransInfo.getCan_trans_coin()));
                } else {
                    mDataBind.transCoin.setText(String.valueOf(mTransInfo.getStock_tax()));
                }
                break;
            case R.id.last_transfer:
//                if (UserManager.getUserBean().getTax_level() < 0) {
//                    return;
//                }
                showProgress();
                addSubscribe(RetrofitHelper.getApis().lastTransfer(Collections.emptyMap())
                        .compose(RxHelper.toMain())
                        .subscribe(respBean -> {
                            hideProgress();
                            if (respBean.isCodeFail()) {
                                showToast(respBean.getMsg());
                                return;
                            }

                            List<LastTrans> list = respBean.getData();
                            Dialogs.showWarehouseDetails(this, list, (dialog, which) -> {
                                mDataBind.toUid.setText(list.get(which).getId());
                            });
                        }, RxHelper.getHideProgressConsumer(this)));
                break;
            case R.id.my_qr:
                if (UserManager.notLogin()) {
                    showToast("请先登录");
                    return;
                }
                addSubscribe(new RxPermissions(this)
                        .request(Constants.LOCATION2)
                        .subscribe(aBoolean -> {
                            if (!aBoolean) {
                                showToast("请授予应用定位权限");
                                return;
                            }
                            showProgress();
                            AmapHelper.startLocation(mContext, aMapLocation -> getMyQr());
                        }));
//                AmapHelper.startLocation(mContext, aMapLocation -> getMyQr());
                break;
            case R.id.verify_code:
                if (!mDataBind.verifyCode.getText().toString().equals("获取验证码")) {
                    return;
                }
                BusinessHelper.sendVerifyCode(this, this::countDownVerifyCode);
                break;

            case R.id.coin_type:
                toggleSourceType(true);
                break;
            case R.id.stock_type:
                toggleSourceType(false);
                break;

            case R.id.trans_in:
            case R.id.trans_out:
                if (mTransInfo.getHave_pay_password() == 0) {
                    UiHelper.showConfirmActionDialog(mContext, "您还没有设置支付密码，是否前往设置"
                            , (dialog, which) -> {
                                //
                                Router.turnTo(mContext, PayPwdSettingActivity.class).start();
                                finish();
                            });
                    return;
                }
                int type = v.getId() == R.id.trans_in ? 10 : 20;
                Dialogs.showStockTran(mContext, mTransInfo, type, (amount, payPwd) -> {
                    //
                    BusinessHelper.onStockTrans(TransActivity.this, type, amount, payPwd, () -> {
                        //
                        onLoadData();
                    });
                });
                break;

            case R.id.apply:
                if (mTransInfo.getNeed_code_verify() == 0 && StringHelper.isEmpty(mDataBind.payPwd)) {
                    UiHelper.showToast("请输入支付密码");
                    return;
                }

                if (mTransInfo.getNeed_code_verify() == 1 && StringHelper.isEmpty(mDataBind.code)) {
                    UiHelper.showToast("请输入验证码");
                    return;
                }

                if (StringHelper.isEmpty(mDataBind.toUid)) {
                    UiHelper.showToast("请输入好友账号");
                    return;
                }

                if (StringHelper.isEmpty(mDataBind.transCoin)) {
                    UiHelper.showToast("请输入转赠数量");
                    return;
                }

                //输入的
                double sr = Double.parseDouble(mDataBind.transCoin.getText().toString());
                if (sr <= 0) {
                    UiHelper.showToast("请输入转赠数量");
                    return;
                }
                //剩余的
                double sy = Double.parseDouble(mTransInfo.getStock_tax());
                if (sy < sr) {
                    UiHelper.showToast("账户门票不足");
                    return;
                }
//                double c = 0;
//                try {
//                    c = Double.parseDouble(mDataBind.transCoin.getText().toString());
//                } catch (Exception e) {
//
//                }
//                if (c >= 50 && !mDataBind.check.isChecked()) {
//                    UiHelper.showToast("本次转赠须二次确认");
//                    return;
//                }
                showProgress();
                Map<String, String> map3 = new HashMap<>();
                map3.put("s_uid", mDataBind.toUid.getText().toString());
                addSubscribe(RetrofitHelper.getApis().searchById(map3)
                        .compose(RxHelper.toMain())
                        .subscribe(respBean -> {
                            hideProgress();
                            if (respBean.isCodeFail()) {
                                UiHelper.setVisibleElseGone(mDataBind.searchUserField, false);
                                showToast(respBean.getMsg());
                                return;
                            }
                            SearchUidTrans bean = respBean.getData();
                            name = bean.getId_card_name();
                            mobile = bean.getMobile();
                            mDataBind.userInfoText.setText(bean.getId_card_name() + "    " + bean.getMobile());
                            mDataBind.userInfoRole.setText(bean.getRole_text());
                            mDataBind.wxAccount.setText(bean.getWx_account());

                            TransferTipsDialog.TransferTipsInfo tipsInfo = new TransferTipsDialog.TransferTipsInfo();
                            tipsInfo.title = "您即将转赠【" + mDataBind.transCoin.getText().toString() + " 门票】到" + UiHelper.getString(R.string.app_name) + "用户";
                            tipsInfo.number = mDataBind.toUid.getText().toString();
                            tipsInfo.name = bean.getId_card_name();
                            tipsInfo.phone = bean.getMobile();
                            if (StringHelper.isNotEmpty(bean.getWx_account())) {
                                tipsInfo.wx_number = bean.getWx_account();
                            } else {
                                tipsInfo.wx_number = "";
                            }
                            tipsInfo.tips = "发起转赠后将无法撤回，请谨慎操作";
                            TransferTipsDialog dialog = TransferTipsDialog.newInstance(mContext, tipsInfo);
                            dialog.setOnClickListener((dialogInterface, i) -> tran());
                            dialog.show(getSupportFragmentManager());
                        }, RxHelper.getHideProgressConsumer(this)));
                break;
            case R.id.tax_level:
            case R.id.tax_level_warn:
                UiHelper.showConfirmDialog(mContext, "1. 活跃度满 100 才有转赠好友门票的权限\n2. 看视频，做任务可以得活跃度\n3. 活跃度可降低转账手续费", (dialog, which) -> {
                });
                break;
            case R.id.energy_field:
                if (UserManager.notLogin()) {
                    return;
                }
                ZzConfigs.toWebActivityByUrl(mContext, "energy");
                break;
            case R.id.layout_tips:
                Router.turnTo(this, DoubleConfirmActivity.class)
                        .putExtra("status", 1)
                        .start();
                break;
            case R.id.warehouse_details:
                //仓库明细
//                List<String> list = new ArrayList<>();
//                for (int i = 0; i < 10; i++) {
//                    list.add("" + i);
//                }
//                Dialogs.showWarehouseDetails(TransActivity.this , list);
                Router.turnTo(mContext, StockRecordActivity.class).putExtra("total", mTransInfo.getStock()).start();
                break;
            case R.id.transfer_description:
                Router.turnTo(this, TransferDescriptionActivity.class).start();
                break;
        }
    }

    private void getMyQr() {
        BusinessHelper.checkGps(TransActivity.this, () -> {
            if (AmapHelper.mAMapLocation != null) {
                uploadLocationInfo(AmapHelper.mAMapLocation);
                return;
            }
            // loc
            AmapHelper.startLocation(mContext, this::uploadLocationInfo);
        });
    }

    void uploadLocationInfo(AMapLocation aMapLocation) {
        //
        if (aMapLocation == null) {
            showToast("没有获取到位置信息");
            return;
        }

        // 加载配置，同步给后端
        BusinessHelper.loadIndexConfig(bool -> {
            hideProgress();
            if (!bool) {
                showToast("同步信息，网络异常");
                return;
            }
            // 显示转赠码
            Map<String, String> map = new HashMap<>();
            map.put("id", "11040");
            map.put("uid", UserManager.getUserId());
            String content = UrlUtil.buildUrl(Constants.Url.Route_App_Url, map);
            Dialogs.showTransQr(thisActivity, content);
        });
    }

    private String name;
    private String mobile;

    private void tran() {
        try {
            String coinCount = mDataBind.transCoin.getText().toString();
            if (Float.parseFloat(coinCount) >= mTransInfo.getVerify_coin()) {
                CompleteLastNameDialog.CompleteLastNameInfo nameInfo = new CompleteLastNameDialog.CompleteLastNameInfo();
                nameInfo.name = name;
                nameInfo.phone = mobile;
                CompleteLastNameDialog dialog = CompleteLastNameDialog.newInstance(mContext, nameInfo);
                dialog.setOnClickListener(str -> startTran(str));
                dialog.show(getSupportFragmentManager());
                return;
            }
            startTran("");
        } catch (Exception ignore) {
        }
    }

    private void startTran(String surname) {
        showProgress();
        Map<String, String> map = new HashMap<>();
        map.put("to_uid", mDataBind.toUid.getText().toString());
        map.put("amount", mDataBind.transCoin.getText().toString());
        map.put("code", mDataBind.code.getText().toString());
        map.put("type", String.valueOf(mCurCoinType ? 10 : 20));
        map.put("pay_pwd", mDataBind.payPwd.getText().toString());
        map.put("surname", surname);
        //是否二次确认0否1是
        map.put("is_confirm", mDataBind.check.isChecked() ? "1" : "0");
        Observable<RespBean> api;
        if (mTransInfo.getNeed_code_verify() == 1) {
            api = RetrofitHelper.getApis().transferByCode(map);
        } else {
            api = RetrofitHelper.getApis().transferByPwd(map);
        }
        addSubscribe(api.compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeFail()) {
                        if ("3010".equals(respBean.code)) {
                            UiHelper.showConfirmDialog(mContext, respBean.getMsg(), null);
                            return;
                        }
                        showToast(respBean.getMsg());
                        return;
                    }
                    UiHelper.showConfirmDialog(mContext, respBean.getMsg(), (dialog, which) -> {
                        if (which == DialogInterface.BUTTON_POSITIVE) {
                            RxBus.get().postEvent(Constants.Event.Expect_Refresh_Dashboard);
                            finish();
                        }
                    });
                }, RxHelper.getHideProgressConsumer(this)));
    }

    /**
     * tab 切换，
     *
     * @param checkCoin true=coin，false=stock
     */
    private void toggleSourceType(boolean checkCoin) {
        mCurCoinType = checkCoin;
        mDataBind.typeCheckField.setBackgroundResource(checkCoin ? R.drawable.trans_type_coin_bg : R.drawable.trans_type_stock_bg);
        UiHelper.setVisibleElseGone(mDataBind.coinTypeFiled, checkCoin);
        UiHelper.setVisibleElseGone(mDataBind.stockTypeFiled, !checkCoin);
//        mDataBind.deductTaxCoin.setTextColor(UiHelper.getColor(checkCoin ? R.color.red : R.color.themeTextDark));
//        mDataBind.transCoin.setText("");

        if (mTransInfo == null) {
            return;
        }

        if (checkCoin) {
            mDataBind.canTranTip.setText("(当前可转赠门票数 " + mTransInfo.getCan_trans_coin() + ")");
        } else {
            mDataBind.canTranTip.setText("(仓库可转赠 " + mTransInfo.getStock_tax() + ")");
        }
    }

    private void setGive() {
        mDataBind.apply.setEnabled(false);
        mDataBind.apply.setAlpha(0.5f);
        mDataBind.toUid.addTextChangedListener(textWatcher);
        mDataBind.transCoin.addTextChangedListener(textWatcher);
        mDataBind.payPwd.addTextChangedListener(textWatcher);
        mDataBind.code.addTextChangedListener(textWatcher);
    }

    private final TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            give();
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };

    private void give() {
        boolean pwd = false;
        if (mDataBind.payPwdField.getVisibility() == View.VISIBLE) {
            pwd = isEmpty(mDataBind.payPwd);
        }
        boolean code = false;
        if (mDataBind.payCodeField.getVisibility() == View.VISIBLE) {
            code = isEmpty(mDataBind.code);
        }
        if (isEmpty(mDataBind.toUid) || isEmpty(mDataBind.transCoin) || pwd || code) {
            mDataBind.apply.setEnabled(false);
            mDataBind.apply.setAlpha(0.5f);
        } else {
            mDataBind.apply.setEnabled(true);
            mDataBind.apply.setAlpha(1f);
        }
    }

    private boolean isEmpty(EditText editText) {
        return editText.getText() == null || editText.getText().toString().length() == 0;
    }
}
